from PIL import Image
import sys
import os

def pad_image(image, target_size):

    """
    :param image: input image
    :param target_size: a tuple (num,num)
    :return: new image
    """

    iw, ih = image.size  # 原始图像的尺寸
    w, h = target_size  # 目标图像的尺寸

    print("original size: ",(iw,ih))
    print("new size: ", (w, h))

    scale = min(w / iw, h / ih)  # 转换的最小比例

    # 保证长或宽，至少一个符合目标图像的尺寸 0.5保证四舍五入
    nw = int(iw * scale+0.5)
    nh = int(ih * scale+0.5)

    print("now nums are: ", (nw, nh))

    image = image.resize((nw, nh), Image.BICUBIC)  # 更改图像尺寸，双立法插值效果很好
    #image.show()
    new_image = Image.new('RGB', target_size, (255, 255, 255))  # 生成白色背景
    # // 为整数除法，计算图像的位置
    new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))  # 将图像填充为中间图像，两侧为黑色的样式
    #new_image.show()

    return new_image

def main():
    if len(sys.argv)!=2:
        print("参数错误，请输入文件夹名称\n")
        exit()
    ori_dir = sys.argv[1]
    if not os.path.isdir(ori_dir):
        print("目标参数不是文件夹\n")
        exit()
    # 创建输出文件夹
    out_dir = ori_dir+'-100x100'
    out_dir = os.path.join(ori_dir, out_dir)
    os.mkdir(out_dir)
    flist = os.listdir(ori_dir)
    for f in flist:
        path = os.path.join(ori_dir, f)
        file_ext = f.rsplit('.',maxsplit=1)

        if len(file_ext)!=2:
            continue
        ext = (file_ext[1]).lower()
        if ext!='jpg' and ext!='jpeg':
            continue

        image = Image.open(path)
        size = (100, 100)
        newImage=pad_image(image, size)
        newImage.save(os.path.join(out_dir, f"{file_ext[0]}-100x100.{file_ext[1]}"))

if __name__ == '__main__':
    main()